import Taro from '@tarojs/taro'
import common from '../service/common';
import { WxAppId, WxRedirect, SET_USER_INFO, GET_COMPANY_TYPES, GET_BRAND_LIST, GET_BRAND_BRANCHS, GET_TASK_TYPES, GET_PUBLIC_LIST, SET_TOKEN_INFO, GET_EXPRESS_LIST, SET_ADDRESS_BOOK, GET_ADDRESS_LIST, DEL_ADDRESS_BOOK, EDIT_ADDRESS_INFO, GET_ADDRESS_INFO } from '../utils/constants';
import { getQueryString } from '../utils'

/**
 * 验证用户信息
 * @param {*} token 
 */
export const userStateAuth = (token, callback) => dispatch =>{
  common.userAuthAPI(token).then(res => {
    Taro.hideLoading()
    if(res.code >= 0){
      dispatch(saveUserAuthInfo(res.data))
      Taro.setStorageSync('userAuth', res.data)
     
      const fromUrl = Taro.getStorageSync('order_detail_url')
      if(fromUrl){
        window.location.href = WxRedirect + fromUrl
      }else{
        window.location.href = WxRedirect + '#/pages/main/index'
      }
    }else{
      console.log('user info==', res)
      callback && callback(res)
      dispatch(saveTokenInfo(res))
    }
  }).catch(err => {
    Taro.hideLoading()
    console.log('验证用户 error=', err)
  })
}

export function saveUserAuthInfo(data){
  return {
    type: SET_USER_INFO,
    data  
  }
}

export function saveTokenInfo(data){
  return {
    type: SET_TOKEN_INFO,
    data  
  }
}

/**
 * 网点品牌列表
 */
export const getBrands = () => dispatch => {
  common.brandListAPI().then(res => {
    if(res.code >= 0){
      dispatch(saveBrandList(res.data.list))
    }
  }).catch(err => {
    console.log('品牌列表error=', err)
  })
}

export function saveBrandList(data){
  return {
    type: GET_BRAND_LIST,
    data,
  }
}

/**
 * 快递品牌列表
 */
export const getExpresses = () => dispatch => {
  common.expressListAPI().then(res => {
    if(res.code >= 0){
      dispatch(saveExpressList(res.data.list))
    }
  }).catch(err => {
    console.log('快递品牌列表error=', err)
  })
}

export function saveExpressList(data){
  return {
    type: GET_EXPRESS_LIST,
    data,
  }
}

/**
 * 企业类型
 */
export const getCompanyTypes = () => dispatch => {
  common.companyTypesAPI().then(res => {
    if(res.code >= 0){
      dispatch(saveTypeList(res.data.list))
    }
  }).catch(err => {
    console.log('企业类型error=', err)
  })
}

export function saveTypeList(data){
  return {
    type: GET_COMPANY_TYPES,
    data,
  }
}

/**
 * 品牌分拨列表
 * @param id 品牌id
 */
export const getBranches = (id) => dispatch => {
  common.branchListAPI(id).then(res => {
    if(res.code >= 0){
      dispatch(saveBranchList(res.data.list))
    }
  }).catch(err => {
    console.log('分拨error=', err)
  })
}

export function saveBranchList(data){
  return {
    type: GET_BRAND_BRANCHS,
    data,
  }
}

/**
 * 任务列表
 */
export const getTasks = () => dispatch => {
  common.taskTypesAPI().then(res => {
    if(res.code >= 0){
      dispatch(saveTaskList(res.data.list))
    }
  }).catch(err => {
    console.log('任务列表error=', err)
  })
}

export function saveTaskList(data){
  return {
    type: GET_TASK_TYPES,
    data,
  }
}

/**
 * 新增地址
 * 
 */
export const addAddress2book = (params, callback) => dispatch => {
  common.addressAddAPI(params).then(res => {
    if(res.code >= 0){
      dispatch(saveAddressBook(res.data))
    }
    callback && callback(res)
  }).catch(err => {
    console.log('增加地址error=', err)
  })
}

export function saveAddressBook(data){
  return {
    type: SET_ADDRESS_BOOK,
    data,
  }
}


/**
 * 编辑地址
 * 
 */
export const editAddressInfo = (params, callback) => dispatch => {
  common.addressEditAPI(params).then(res => {
    if(res.code >= 0){
      dispatch(saveAddressEdit(res.data))
    }
    callback && callback(res)
  }).catch(err => {
    console.log('编辑地址error=', err)
  })
}

export function saveAddressEdit(data){
  return {
    type: EDIT_ADDRESS_INFO,
    data,
  }
}

/**
 * 地址信息
 * 
 */
export const getAddressInfo = (id, callback) => dispatch => {
  common.addressInfoAPI(id).then(res => {
    if(res.code >= 0){
      dispatch(saveAddressInfo(res.data))
    }
    callback && callback(res)
  }).catch(err => {
    console.log('地址 info error=', err)
  })
}

export function saveAddressInfo(data){
  return {
    type: GET_ADDRESS_INFO,
    data,
  }
}


/**
 * 删除地址信息
 * 
 */
export const delAddressFromBook = (id, callback) => dispatch => {
  common.addressDeleteAPI(id).then(res => {
    if(res.code >= 0){
      dispatch(saveAddressDel(res.data))
    }
    callback && callback(res)
  }).catch(err => {
    console.log('地址 info error=', err)
  })
}

export function saveAddressDel(data){
  return {
    type: DEL_ADDRESS_BOOK,
    data,
  }
}

/**
 * 地址列表
 * 
 */
export const getAddressBookList = (params, callback) => dispatch => {
  common.addressListAPI(params).then(res => {
    if(res.code >= 0){
      dispatch(saveAddressList(res.data))
      callback && callback(res.data)
    }
  }).catch(err => {
    console.log('地址 info error=', err)
  })
}

export function saveAddressList(data){
  return {
    type: GET_ADDRESS_LIST,
    data,
  }
}

/**
 * 公共数据列表
 * @param type 任务id
 *   traffic_type:运输类型；
 *   traffic_order_state:货运订单状态；
 *   added_service:增值服务；
 *   air_goods_type:航空物品类型；
 *   line_type:专线物品类型；
 *   rej_tra_type:拒绝订单描述信息
 * @param getChild 是否有下级数据
 */
export const getPublicData = (params, callback) => dispatch => {
  let getChild = 0
  if(params.getChild){
    getChild = params.getChild
  }
  common.publicDataAPI(params.type, getChild).then(res => {
    if(res.code >= 0){
      dispatch(savePublicDataList(res.data.list))
      callback && callback(res.data.list)
    }
  }).catch(err => {
    console.log('公共数据列表error=', err)
  })
}

export function savePublicDataList(data){
  return {
    type: GET_PUBLIC_LIST,
    data,
  }
}


/** 微信登录 */
export function wechatLogin(){
  let from = getQueryString('from')
  if(!from){
    from = 'sla_traffic_order'
  }
  const uri = encodeURIComponent(WxRedirect)
	const codeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WxAppId}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${from}#wechat_redirect`

	window.location.href = codeUrl
}

/** 微信签名 */
export const getWxSignutre = (callback) => () => {
 
  const url = window.location.href
  common.wxSignature(url).then(res => {

    wx.config({
      debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.appId, // 必填，公众号的唯一标识
      timestamp: res.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.nonceStr, // 必填，生成签名的随机串
      signature: res.signature,// 必填，签名
      jsApiList: [
        'updateAppMessageShareData'
      ] // 必填，需要使用的JS接口列表
    });
    wx.ready(() =>{
      callback && callback()
    })
    wx.error((wxerr) => {
      console.log('微信config error==', wxerr)
    })
  }).catch(err => {
    console.log('微信注册error==',err)
  })

}

